package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//这个注解表示该类是对控制器进行增强的
public class MyControllerAdvice {

    @ExceptionHandler(Exception.class)
    public String handler(RuntimeException e, HandlerMethod method, HttpServletResponse response){
        e.printStackTrace();
        //如果原本控制器的方法是返回JsonResult数据,现在出异常也应该返回JsonResult
        //获取当前出现异常的方法,判断是否有ResponseBody注解,有就代表需要返回JsonResult
        if(method.hasMethodAnnotation(ResponseBody.class)){
            try {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSON.toJSONString(new JsonResult(false,"系统异常,请联系管理员")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return null;
        }
        return "common/error";
    }
}
